import React, { useEffect, useState } from 'react'
import { useCollection2 } from '../../../../../domain/collection'
import type { CollectionQueryParams } from '../../../../../domain/collection/types/types.ts'
import { useUser } from '../../../../../domain/user/hooks/useUser.ts'
import CollectionList2 from '../../../../../domain/collection/components/CollectionList2.tsx'
import CollectionDetail from '../../../pages/userCenter/collect/CollectionDetail.tsx'

interface UserCollectListProps {
  userId?: number
}

const UserCollectList: React.FC<UserCollectListProps> = ({
  userId: propUserId,
}) => {
  // 获取当前登录用户信息
  const currentUser = useUser()

  // 确定实际使用的用户ID：优先使用传入的propUserId，否则使用当前登录用户的ID
  const targetUserId = propUserId || currentUser?.userId

  const [queryParams, setQueryParams] = useState<CollectionQueryParams>({
    noteId: undefined,
    creatorId: targetUserId,
  })

  // 监听用户ID变化更新查询参数
  useEffect(() => {
    setQueryParams((prev) => ({
      ...prev,
      creatorId: targetUserId,
    }))
  }, [targetUserId])

  // 收藏夹展示模式控制
  const [showCollectionDetail, setShowCollectionDetail] = useState(false)
  // 当前选中的收藏夹ID
  const [selectedCollectionId, setSelectedCollectionId] = useState<number>()

  // 获取收藏夹列表数据
  const { collectionVOList } = useCollection2(queryParams)

  // 切换收藏夹详情显示
  const toggleCollectionDetail = () => {
    setShowCollectionDetail(!showCollectionDetail)
  }

  // 处理收藏夹选择
  const handleSelectCollection = (collectionId: number) => {
    setSelectedCollectionId(collectionId)
    toggleCollectionDetail()
  }

  return (
    <>
      {showCollectionDetail ? (
        <CollectionDetail
          selectedCollectionId={selectedCollectionId}
          toggleShowCollectionDetail={toggleCollectionDetail}
        />
      ) : (
        <div>
          <div className="mb-4 text-lg font-medium">收藏夹</div>
          <CollectionList2
            collectionVOList={collectionVOList}
            toggleShowCollectionDetail={toggleCollectionDetail}
            handleSelectedCollectionId={handleSelectCollection}
            showCollectionOption={false}
          />
        </div>
      )}
    </>
  )
}

export default UserCollectList
